package com.example.udptestdemo.servers;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import org.greenrobot.eventbus.EventBus;

import com.example.udptestdemo.events.SocketRecvTimeOutEvent;


public abstract class BaseSocket {

	private int mSoTimeout=3000;
	private int mbindPort;
	
	private boolean mActive=false;
	
	protected DatagramSocket  mBaseSocket;
	
	public BaseSocket(int bindPort) throws SocketException{
		this.mbindPort =bindPort;
		mBaseSocket = new DatagramSocket(mbindPort);
		mBaseSocket.setSoTimeout(mSoTimeout);
	}
	
	public BaseSocket(int bindPort,int sotimeout) throws SocketException{
		this.mbindPort=bindPort;
		this.mSoTimeout=sotimeout;
		mBaseSocket = new DatagramSocket(mbindPort);
		mBaseSocket.setSoTimeout(mSoTimeout);
	}
	
	
	protected void startWork(){
		if(mActive)
			throw new RuntimeException("接收进程正在运行不需要重复启动");
		mActive=true;
		Thread thread = new Thread(_recv_runnable);
		thread.start();
	}
	
	
	protected abstract void dealWithData(DatagramPacket packet);
	
	
	private Runnable _recv_runnable =new Runnable(){

		@Override
		public void run() {
			while(mActive){
				 byte[] data = new byte[1024 * 10];   //10k
				 DatagramPacket packet = new DatagramPacket(data, data.length);
				 try{
					 mBaseSocket.receive(packet);
					 dealWithData(packet);
				 }catch(SocketTimeoutException e){
					// EventBus.getDefault().post(new SocketRecvTimeOutEvent());
				 }catch(IOException e){
					 e.printStackTrace();
				 }catch(Exception e){
					 e.printStackTrace();
				 }
			}
			
		}
		
	};
	
	public void sendDatagramPacket(DatagramPacket packet) throws IOException{
		if(!mBaseSocket.isClosed()){
			mBaseSocket.send(packet);
		}
	}
	
	/**
	 * 结束 释放资源
	 */
	public void onRelease(){
		mActive=false;
		if(null!=mBaseSocket)
			mBaseSocket.close();
	}
}
